<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */

namespace app\admin\controller;

use app\BaseController;
use app\result\admin\AdminResult;
use think\App;
use think\Exception;
use think\exception\HttpResponseException;
use think\facade\Config;
use think\facade\Route;
use think\facade\Session;
use think\facade\View;
use think\Response;

class BaseAdmin extends BaseController
{

    protected $admin_id = 0;
    protected $kefu_id = 10000;//客服id
    protected $admin;
    protected $unauthorized = [];//不需要鉴权验证的接口

    protected $notAuth = [];// 不需要登录
    protected $param;
    protected $objResult = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->initialize();

    }


    private function login_timeout($msg = '登录过期')
    {
        if ($this->request->isAjax()) {
            data_return($msg, 401);
        } else {
            header('Location: ' . url('/admin/login/index'));
        }
        return true;
    }

    protected function initialize()
    {
        $this->param = request()->filter('trim,htmlspecialchars')->param();

        $controller = request()->controller();
        $action = request()->action();

        if ($this->notAuth && !in_array($action, $this->notAuth)) {
            return true;
        }
        $token = Session::get('admin_token');
        if (!$token) {
            //来自浏览器
            $token = request()->header('Authorization');
            if (empty($token)) {
                //兼容特殊组件无法设置header，比如ueditor
                $token = input('Authorization', '', 'trim');
                if (!$token) {
                    bs_log('没有token', 'debug' . __LINE__, 'no_token.log');
                    return $this->login_timeout();
                }
            }
        }

        $token = str_replace('Bearer ', '', $token);
        $checkToken = (new AdminResult())->check_token($token, '*');
        if ($checkToken['code'] != 0) {
            bs_log('没有token', 'debug' . __LINE__, 'no_token.log');
            return $this->login_timeout($checkToken['msg']);
        }
        $admin = $checkToken['data'];
        if (!$admin) {
            bs_log('没有token', 'debug' . __LINE__, 'no_token.log');
            return $this->login_timeout();
        } else {
            $this->admin = $admin;
            $this->admin_id = $admin['admin_id'];
            !defined('ADMIN_ID') && define('ADMIN_ID', $this->admin_id);
        }


        $url = request()->pathinfo();//路由
        if ($admin['role_id'] > 0) {
            //非超级管理员
            if (!in_array($url, $this->unauthorized)) {
                $this->objResult = new AdminResult();
                if (stripos($url, '/') !== 0) {
                    $url = '/' . $url;
                }
                if (in_array($url, ['/', '/admin', '/menus/my_list', '/index'])) {
                    return true;
                }
                if (str_ends_with($url, '/list_config')) {
                    return true;
                }

                $checkAuth = $this->objResult->check_permission($admin['role_id'], $url);
                if (!$checkAuth) {
                    /*bs_log([
                        'url' => $url,
                        //'admin' => $admin,
                        'action' => $action,
                        'controller' => $controller,
                        'method' => request()->method(),
                        'isAjax' => $this->request->isAjax(),

                    ], '无权', 'admin_access_log.log');*/
                    if ($this->request->isAjax()) {
                        if ($this->request->isOptions()) {
                            return true;
                        }
                        throw new HttpResponseException(
                            response('无权访问', 403)
                        );

                    } else {
                        echo '<script>alert("您没有权限访问");</script>';
                        throw new HttpResponseException(
                            response('无权访问', 403)
                        );
                    }

                }
            }
        }
        //bs_log(['url' => $url, 'admin' => $admin], 'info', 'admin_access_log.log');
    }

    /**
     * 渲染模板
     * @param $tpl  string 模板路径，比如 features/index
     * @param $vars array 模板变量, 比如 ['title' => '标题']
     * @return string
     *
     */
    protected function view($tpl, $vars = []): string
    {
        return View::fetch($tpl, $vars);
    }
}
